import {defineStore} from "pinia"
import {ref} from "vue"
import {useThrottleFn} from "@vueuse/core"
import type {PaginationProps} from "naive-ui"
import type {UserType} from "@config"
import {useUserApi} from "@user"
import {ResType, ResObjPropNameConst} from 'st-common-req'

/**
 * 系统用户管理中用户相关信息状态管理仓库
 */
export const useSysUserStore = defineStore('sysUserStore', () => {
  // 表格加载状态
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref<UserType[]>([])
  // 分页信息
  const pagination = ref<PaginationProps>({
    page: 1,
    pageSize: 10,
    itemCount: 0,
    showSizePicker: true,
    showQuickJumper: true,
    pageSizes: [10, 20, 30, 40, 50],
  })

  const userApi = useUserApi()

  /**
   * 获取表格加载状态
   */
  const getUserTableLoading = () => tableLoading.value

  /**
   * 获取表格数据
   */
  const getUserTableData = () => tableData.value

  /**
   * 设置表格数据
   * @param newUserTableData 新的表格数据
   */
  const setUserTableData = (newUserTableData: UserType[]) => {
    tableData.value = newUserTableData
    return tableData.value
  }

  /**
   * 根据请求获取用户数据
   * @param filter 过滤条件
   */
  const getUserDataByReq = useThrottleFn(async (filter?: Record<string, any>): Promise<ResType> => {
    try {
      tableLoading.value = true
      const {data, total} = await userApi.getUserList({
        page: pagination.value.page,
        pageSize: pagination.value.pageSize,
        ...filter,
      })
      tableData.value = data
      pagination.value.itemCount = total
      return {
        [ResObjPropNameConst.STATUS]: true,
        [ResObjPropNameConst.MESSAGE]: '获取用户数据成功',
      }
    } catch (error) {
      return {
        [ResObjPropNameConst.STATUS]: false,
        [ResObjPropNameConst.MESSAGE]: '获取用户数据失败',
      }
    } finally {
      tableLoading.value = false
    }
  }, 1000)

  /**
   * 删除用户
   * @param rowKeys 用户ID列表
   * @param cascade 是否级联删除
   */
  const deleteUser = async (rowKeys: (string | number)[], cascade: boolean): Promise<ResType> => {
    try {
      if (Array.isArray(rowKeys)) {
        await Promise.all(rowKeys.map(id => userApi.deleteUser(id.toString())))
      } else {
        await userApi.deleteUser(rowKeys.toString())
      }
      return {
        [ResObjPropNameConst.STATUS]: true,
        [ResObjPropNameConst.MESSAGE]: '删除用户成功',
      }
    } catch (error) {
      return {
        [ResObjPropNameConst.STATUS]: false,
        [ResObjPropNameConst.MESSAGE]: '删除用户失败',
      }
    }
  }

  /**
   * 处理分页变化
   * @param page 页码
   */
  const handlePageChange = async (page: number) => {
    pagination.value.page = page
    await getUserDataByReq()
  }

  return {
    tableLoading,
    tableData,
    pagination,
    getUserTableLoading,
    getUserTableData,
    setUserTableData,
    getUserDataByReq,
    deleteUser,
    handlePageChange,
  }
}) 